<template>
  <div class="step-edit">
    <u-steps :current="current" style="margin-bottom: 32px; ">
      <u-step title="基本信息" description="选择模板类型，填写模板信息" />
      <u-step title="字段编辑" description="选择编辑模板字段" />
      <u-step title="模板生成" description="模板确认及发布" />
    </u-steps>
    <div class="step-component">
      <dynamics-form
        v-if="current === 0"
        ref="form"
        storage-custom
        storage-key="fieldTemplate"
        :model="model"
        :setting="setting"
        :label-width="100"
        style="width: 500px"
      />
      <div v-if="current === 1" class="step-component-full">
        <u-alert type="info">
          外呼明细字段模板，会提供系统内置的所有可获取的内置字段，您可以在他们中选择您需要应用到策略配置的相关字段。
        </u-alert>
        <u-transfer
          v-model:target-keys="allKeys"
          show-search
          :titles="['可选字段', '已选字段']"
          :data-source="[...systemFields, ...commonFields]"
          :remove-source="false"
          :filter-method="(val, item) => item.title.indexOf(val) > -1 || item.key.indexOf(val) > -1"
          :list-style="{ maxHeight: '600px', minHeight: '400px' }"
        >
          <template #renderItem="{ item }">
            <span>
              {{ item.title }}
              <br>
              {{ item.key }}
            </span>
          </template>
          <template
            #children="{
              props: { side, selectedKeys, filteredData },
              methods: { onSelect }
            }"
          >
            <u-tree
              v-if="side === 'left'"
              :tree-data="getFilterTreeData(filteredData)"
              :checked-keys="[...allKeys, ...selectedKeys]"
              checkable
              check-strictly
              default-expand-all
              @check="
                checkedKeys => {
                  handleCheck(checkedKeys, [...allKeys, ...selectedKeys], onSelect);
                }
              "
            >
              <template #title="{node}">
                <span class="custom-tree-title">
                  {{ node.title }}
                  <br>
                  {{ node.key }}
                </span>
              </template>
            </u-tree>
          </template>
        </u-transfer>
      </div>
      <div v-if="current === 2" style="width: 100%">
        <u-table
          :data="[...selectedSystemFields, ...selectedCommonFields]"
          :columns="fieldsColumns"
          style="width: 100%"
        />
      </div>
    </div>
    <div class="operate-container">
      <u-button class="m-r-1" @click="goBack">
        返回
      </u-button>
      <u-button v-if="current > 0" class="m-r-1" @click="handlePrev">
        上一步
      </u-button>
      <u-button v-if="current < 2" type="primary" @click="handleNext">
        下一步
      </u-button>
      <u-button v-if="current === 2" type="primary" :loading="loading" @click="handleNext">
        完成
      </u-button>
    </div>
  </div>
</template>
<script>
import {
  ref, reactive, computed, onMounted
} from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { DynamicsForm, message } from '@bairong/vix'
import {
  getAllFieldsApi,
  addFieldApi,
  updateFieldApi,
  getTypeFieldsApi,
  getFieldDetailApi,
  checkNameExistsApi
} from '@api/field'
import { fieldsColumns } from '../columns'

export default {
  name: 'FieldEdit',
  components: {
    DynamicsForm
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const current = ref(0)
    const form = ref(null)
    const loading = ref(false)
    const model = reactive({
      variableName: '',
      remark: ''
    })
    const setting = [
      {
        name: 'variableName',
        label: '模板名称',
        type: 'input',
        disabled: route.name === 'fieldEdit',
        rules: [
          { required: true, message: '请填写模板名称', trigger: 'blur' },
          {
            pattern: /^[\u4e00-\u9fa5\dA-Za-z-_]{2,30}$/,
            message: '仅支持中英文、数字、中划线、下划线，限制2-30字符',
            trigger: 'blur'
          }
        ],
        tips: '支持中英文、数字、中划线、下划线，限制2-30字符'
      },
      {
        name: 'remark',
        label: '描述',
        type: 'textarea',
        rules: [{ max: 300, message: '最大长度300', trigger: 'change' }],
        props: {
          maxlength: 300,
          showWordLimit: true,
          placeholder: '请输入描述信息，限制0-300个字符'
        }
      }
    ]

    const commonFields = ref([])
    const systemFields = ref([])
    const allKeys = ref([])
    const selectedCommonFields = computed(() => commonFields.value.filter(a => allKeys.value.includes(a.key)))
    const selectedSystemFields = computed(() => systemFields.value.filter(a => allKeys.value.includes(a.key)))

    const treeData = computed(() => [
      {
        title: '内置字段',
        key: 'system',
        checkable: false,
        children: systemFields.value.map(t => ({ ...t, disabled: allKeys.value.includes(t.key) }))
      },
      {
        title: '变量字段',
        key: 'common',
        checkable: false,
        children: commonFields.value.map(a => ({ ...a, disabled: allKeys.value.includes(a.key) }))
      }
    ])

    const getFilterTreeData = filteredData => {
      const filteredKeys = filteredData.map(f => f.key)
      if (filteredKeys.length) {
        return treeData.value.map(t => ({
          ...t,
          children: t.children.filter(c => filteredKeys.includes(c.key))
        }))
      }
      return treeData.value
    }

    const handleCheck = (keys, oldKeys, onSelect) => {
      const eventKey = [...keys, ...oldKeys].reduce((prev, next) => {
        const idx = prev.indexOf(next)
        if (idx !== -1) {
          prev.splice(idx, 1)
        } else {
          prev.push(next)
        }
        return prev
      }, [])
      const isChecked = keys.includes(eventKey[0])
      onSelect(eventKey[0], isChecked)
    }

    const goBack = () => {
      router.back()
    }

    onMounted(() => {
      // TODO: 线上预发参数不一致
      const apicode = window.location.origin !== 'https://robotaiop.100credit.com' ? 110 : 7410123
      getAllFieldsApi({ apicode }).then(res => {
        commonFields.value = res.map(f => ({
          ...f,
          key: f.varEnName,
          title: f.varCnName,
          regex: f.regex,
          source: 'common',
          sourceText: '变量字段'
        }))
      })
      getTypeFieldsApi({ variableType: 1 }).then(res => {
        const lists = JSON.parse(res.jsonData)
        systemFields.value = lists.map(f => ({
          ...f,
          key: f.eName,
          title: f.name,
          source: 'system',
          sourceText: '内置字段'
        }))
      })
      if (route.name === 'fieldEdit' || route.name === 'fieldCopy') {
        const { variableId } = route.query
        getFieldDetailApi({ variableId }).then(res => {
          const {
            variableName, remark, status, jsonData, outboundCallProcess
          } = res
          model.variableName = variableName
          model.remark = remark
          model.status = status
          if (route.name === 'fieldEdit') {
            model.variableId = variableId
          }
          allKeys.value = [
            ...JSON.parse(jsonData).map(a => a.eName),
            ...JSON.parse(outboundCallProcess).map(a => a.eName)
          ]
        })
      }
    })

    const handlePrev = () => {
      current.value -= 1
    }

    const generateParams = () => {
      const params = {
        ...model,
        status: model.status || 1,
        variableType: 2,
        jsonData: JSON.stringify(
          selectedCommonFields.value.map(s => ({
            name: s.varCnName,
            eName: s.varEnName,
            regex: s.regex
          }))
        ),
        outboundCallProcess: JSON.stringify(
          selectedSystemFields.value.map(s => ({ name: s.name, eName: s.eName }))
        )
      }
      return params
    }

    const handleNext = () => {
      if (current.value === 0) {
        form.value
          .validate()
          .then(() => {
            if (route.name !== 'fieldEdit') {
              checkNameExistsApi({ variableName: model.variableName })
                .then(res => {
                  if (!res) {
                    current.value += 1
                  } else {
                    message.error('模板名称已存在')
                  }
                })
                .catch(err => {
                  message.error(err)
                })
            } else {
              current.value += 1
            }
          })
          .catch(err => {
            console.log(err)
          })
        return
      }
      if (current.value === 1) {
        if (!allKeys.value.length) {
          message.error('请先选择模板字段')
          return
        }
        current.value += 1
        return
      }
      if (current.value === 2) {
        if (allKeys.value.length > 200) {
          message.error('最大字段数量不能超过200个!')
          return
        }
        const params = generateParams()
        loading.value = true
        if (route.name === 'fieldAdd' || route.name === 'fieldCopy') {
          const msg = route.name === 'fieldAdd' ? '新建' : '复制'
          addFieldApi(params)
            .then(() => {
              message.success(`${msg}模板成功！`)
              loading.value = false
              goBack()
            })
            .catch(err => {
              message.error(err.message)
              loading.value = false
            })
        }
        if (route.name === 'fieldEdit') {
          updateFieldApi(params)
            .then(() => {
              message.success('编辑模板成功！')
              loading.value = false
              goBack()
            })
            .catch(err => {
              message.error(err.message)
              loading.value = false
            })
        }
      }
    }

    return {
      current,
      form,
      loading,
      model,
      setting,
      commonFields,
      systemFields,
      treeData,
      getFilterTreeData,
      allKeys,
      selectedCommonFields,
      selectedSystemFields,
      handleCheck,
      fieldsColumns,
      handlePrev,
      handleNext,
      goBack
    }
  }
}
</script>
<style lang="less"></style>
